import axios from 'axios';
import sensitiveWordsData from './sensitiveWords.json';
import { chatStorage } from '../../chatStorage';
import { DIFY_CONFIG, PYTHON_SERVICE_CONFIG, DEFAULT_COMPANION_PROFILE } from '../../config';

// 消息类型
export type MessageType = {
  role: "user" | "companion";
  content: string;
  scenario?: string;
  timestamp?: string;
};

// 虚拟恋人回复类型
export type CompanionReply = {
  text: string;
  emotional_state?: any;
  behavior_patterns?: any;
  current_scenario?: string;
};


// 从配置文件获取Dify API配置
const DIFY_API_KEY = DIFY_CONFIG.API_KEY;
const DIFY_API_ENDPOINT = DIFY_CONFIG.API_ENDPOINT;

// API基地址列表 - 从配置文件获取
const API_BASE_URLS = PYTHON_SERVICE_CONFIG.BASE_URLS;

// 全局变量，保存当前可用的API基地址
let CURRENT_API_URL = API_BASE_URLS[0];

// 增加 Dify API 超时时间，避免超时错误
const DIFY_TIMEOUT = 30000; // 30秒
const PYTHON_SERVICE_TIMEOUT = 15000; // 15秒
// 调试日志函数
const debugLog = (message: string, data?: any) => {
  if (process.env.NODE_ENV === 'development') {
    console.log(`[DEBUG] ${message}`, data || '');
  }
};

// 敏感词检测接口
export interface SensitiveCheckResult {
  is_sensitive: boolean;
  matched_words: string[];
  sensitivity_level: string | null;
  suggested_response: string | null;
  mood_change: number;
  should_exit: boolean;
}

// 从JSON文件中加载敏感词配置
const highLevelWords = sensitiveWordsData.sensitiveWords.high;
const mediumLevelWords = sensitiveWordsData.sensitiveWords.medium;
const lowLevelWords = sensitiveWordsData.sensitiveWords.low;
const reactions = sensitiveWordsData.reactions;

// 检查API是否可用并选择最佳API URL
const checkApiAvailability = async (): Promise<boolean> => {
  try {
    for (const baseUrl of API_BASE_URLS) {
      try {
        const response = await axios.get(`${baseUrl}`, {
          timeout: 2000 // 2秒超时
        });
        
        if (response.status === 200) {
          debugLog(`找到可用的API: ${baseUrl}`);
          CURRENT_API_URL = baseUrl;
          return true;
        }
      } catch (error) {
        debugLog(`API ${baseUrl} 不可用`);
        // 继续尝试下一个
      }
    }
    
    debugLog('所有API都不可用');
    return false;
  } catch (error) {
    console.error('检查API可用性出错:', error);
    return false;
  }
};

// 检测文本是否包含敏感词
export const checkSensitiveWords = async (text: string, userId?: string): Promise<SensitiveCheckResult> => {
  try {
    // 先检查API是否可用
    const apiAvailable = await checkApiAvailability();
    
    if (apiAvailable) {
      try {
        const response = await axios.post(`${CURRENT_API_URL}/check-sensitive`, {
          text,
          user_id: userId || 'anonymous'
        }, {
          timeout: 3000
        });
        
        if (response.data) {
          return response.data;
        }
      } catch (error) {
        debugLog('敏感词API请求失败，使用本地检测', error);
      }
    }
    
    // 如果API不可用或请求失败，使用本地检测
    return localSensitiveCheck(text);
  } catch (error) {
    debugLog('敏感词检测出错', error);
    return localSensitiveCheck(text);
  }
};

// 本地敏感词检测
const localSensitiveCheck = (text: string): SensitiveCheckResult => {
  const lowercaseText = text.toLowerCase();
  
  // 检查高级别敏感词
  const matchedHigh = highLevelWords.filter(word => lowercaseText.includes(word));
  if (matchedHigh.length > 0) {
    return {
      is_sensitive: true,
      matched_words: matchedHigh,
      sensitivity_level: "高", 
      suggested_response: reactions.high.response,
      mood_change: reactions.high.mood_change,
      should_exit: reactions.high.should_exit
    };
  }
  
  // 检查中级别敏感词
  const matchedMedium = mediumLevelWords.filter(word => lowercaseText.includes(word));
  if (matchedMedium.length > 0) {
    return {
      is_sensitive: true,
      matched_words: matchedMedium,
      sensitivity_level: "中",
      suggested_response: reactions.medium.response,
      mood_change: reactions.medium.mood_change,
      should_exit: reactions.medium.should_exit
    };
  }
  
  // 检查低级别敏感词
  const matchedLow = lowLevelWords.filter(word => lowercaseText.includes(word));
  if (matchedLow.length > 0) {
    return {
      is_sensitive: true,
      matched_words: matchedLow,
      sensitivity_level: "低",
      suggested_response: reactions.low.response,
      mood_change: reactions.low.mood_change,
      should_exit: reactions.low.should_exit
    };
  }
  
  return {
    is_sensitive: false,
    matched_words: [],
    sensitivity_level: null,
    suggested_response: null,
    mood_change: 0,
    should_exit: false
  };
};



// 发送消息给虚拟恋人
export const sendCompanionMessage = async (input: string, styleType: string = "温柔型") => {
  try {
    // 尝试直接调用Dify工作流API
    try {
      debugLog('尝试调用Dify工作流API');
      
      // 构建请求数据
      const messages = chatStorage.getHistory();
      
      // 添加当前消息
      const userMessage: MessageType = {
        role: "user",
        content: input
      };
      
      // 保存历史记录
      chatStorage.addMessage(userMessage);
      
      // 构建对话历史字符串，格式与Python后端一致
      const conversation_history = messages
        .slice(-8) // 保留最近8条消息，与Python后端一致
        .map(msg => `${msg.role === 'companion' ? 'assistant' : msg.role}：${msg.content}`)
        .join('\n');
      
      // 从配置文件获取工作流ID
      const WORKFLOW_ID = DIFY_CONFIG.WORKFLOW_ID;
      
      // 构建工作流请求数据
      const workflowData = {
        workflow_id: WORKFLOW_ID,
        inputs: {
          user_input: input,
          conversation_history: conversation_history,
          style_prompt: `请以${styleType}的风格回复用户`,
          growth_log: "", // 前端暂不处理成长日志
          emotional_state: "其他", // 默认情感状态
          system_prompt: `你是一个${styleType}的虚拟女友小悠。保持自然、生活化的对话风格，像真实情侣一样交流。`,
          user_profile: {
            emotional_state: "normal",
            behavior_patterns: {
              communication_style: styleType
            }
          }
        },
        response_mode: "blocking",
        user: DIFY_CONFIG.USER_ID
      };
      
      debugLog('发送Dify工作流请求', workflowData);
      
      // 调用Dify工作流API
      const response = await axios.post(
        `${DIFY_API_ENDPOINT}/workflows/run`, 
        workflowData,
        {
          headers: {
            'Authorization': `Bearer ${DIFY_API_KEY}`,
            'Content-Type': 'application/json'
          },
          timeout: DIFY_TIMEOUT // 使用增加的超时时间
        }
      );
      
      debugLog('收到Dify工作流响应', response.data);
      
      // 处理工作流响应，支持多种可能的响应格式
      let replyText = '';
      
      // 检查各种可能的响应格式
      if (response.data && response.data.data && response.data.data.outputs) {
        // 标准工作流输出格式
        const outputs = response.data.data.outputs;
        if (outputs.text) {
          replyText = outputs.text;
        } else if (outputs.answer) {
          replyText = outputs.answer;
        } else if (typeof outputs === 'string') {
          replyText = outputs;
        } else if (typeof outputs === 'object') {
          // 尝试从对象中找到可能的文本字段
          const possibleTextFields = ['answer', 'text', 'content', 'response', 'message', 'reply'];
          for (const field of possibleTextFields) {
            if (outputs[field] && typeof outputs[field] === 'string') {
              replyText = outputs[field];
              break;
            }
          }
          
          // 如果没找到文本字段，但outputs是对象，可能是直接返回了JSON
          if (!replyText && Object.keys(outputs).length > 0) {
            // 检查是否有answer字段是JSON字符串
            if (outputs.answer && typeof outputs.answer === 'string') {
              try {
                const parsed = JSON.parse(outputs.answer);
                if (parsed && parsed.answer && typeof parsed.answer === 'string') {
                  replyText = parsed.answer;
                }
              } catch (e) {
                // 不是有效的JSON，使用原始文本
                replyText = outputs.answer;
              }
            }
          }
        }
      } else if (response.data && response.data.outputs) {
        // 直接输出格式
        const outputs = response.data.outputs;
        if (outputs.answer && typeof outputs.answer === 'string') {
          replyText = outputs.answer;
        } else if (outputs.text && typeof outputs.text === 'string') {
          replyText = outputs.text;
        }
      } else if (response.data && response.data.answer) {
        // 简单输出格式
        replyText = response.data.answer;
      } else if (response.data && typeof response.data === 'string') {
        // 直接返回字符串
        replyText = response.data;
      }
      
      // 检查回复是否是JSON字符串，如果是则尝试提取文本内容
      if (replyText && typeof replyText === 'string') {
        if (replyText.trim().startsWith('{') && replyText.trim().endsWith('}')) {
          try {
            const parsedJson = JSON.parse(replyText);
            if (parsedJson.answer && typeof parsedJson.answer === 'string') {
              replyText = parsedJson.answer;
            } else if (parsedJson.text && typeof parsedJson.text === 'string') {
              replyText = parsedJson.text;
            } else if (parsedJson.content && typeof parsedJson.content === 'string') {
              replyText = parsedJson.content;
            }
          } catch (e) {
            // 解析失败，保持原样
            debugLog('JSON解析失败，使用原始文本', e);
          }
        }
      }
      
      // 如果仍然没有找到有效的回复文本，抛出错误
      if (!replyText) {
        debugLog('未能从响应中提取文本', response.data);
        throw new Error("Dify工作流API响应格式不正确");
      }
      
      // 保存历史记录
      const companionMessage: MessageType = {
        role: "companion",
        content: replyText
      };
      
      chatStorage.addMessage(companionMessage);
      
      return {
        content: replyText,
        mood: 100, // 默认心情值
        imageUrl: null
      };
    } catch (error: any) {
      console.error('Dify工作流API请求失败:', error);
      
      // 如果是超时错误，返回一个友好的响应而不是尝试使用Python服务
      if (error.code === 'ECONNABORTED' || (error.message && error.message.includes('timeout'))) {
        return {
          content: "抱歉，我现在有点忙，请稍后再试～",
          mood: 80,
          imageUrl: null
        };
      }
      
      // 如果是其他错误，尝试使用Python服务作为备用
      // 检查API是否可用
      const apiAvailable = await checkApiAvailability();
      
      if (!apiAvailable) {
        // 如果Python服务也不可用，返回一个友好的响应
        return {
          content: "我好像遇到了一些问题，不过我很快就会恢复的～",
          mood: 70,
          imageUrl: null
        };
      }
      
      // 构建正确的请求格式，包含历史消息
      const messages = chatStorage.getHistory();
      
      // 构建请求数据
      const requestData = {
        messages: messages.map(msg => ({
          role: msg.role,
          content: msg.content,
          scenario: msg.scenario || 'casual'
        })),
        style_type: styleType // 添加风格类型参数
      };
      
      debugLog('发送聊天请求到Python服务', requestData);
      
      const response = await axios.post(`${CURRENT_API_URL}/chat`, requestData, {
        timeout: PYTHON_SERVICE_CONFIG.TIMEOUT
      });
      
      debugLog('收到Python服务聊天响应', response.data);
      
      if (response.data && response.data.reply) {
        // 提取回复文本
        let replyText = response.data.reply;
        
        // 检查回复是否是JSON字符串
        if (typeof replyText === 'string' && replyText.trim().startsWith('{') && replyText.trim().endsWith('}')) {
          try {
            const parsed = JSON.parse(replyText);
            if (parsed.answer) {
              replyText = parsed.answer;
            } else if (parsed.text) {
              replyText = parsed.text;
            } else if (parsed.content) {
              replyText = parsed.content;
            }
          } catch (e) {
            // 解析失败，保持原样
            debugLog('Python服务返回的JSON解析失败', e);
          }
        }
        
        // 保存历史记录
        chatStorage.addMessage({
          role: "companion",
          content: replyText
        });
        
        return {
          content: replyText,
          mood: response.data.mood || 100,
          imageUrl: null
        };
      }
      
      throw new Error("Python服务API响应格式不正确");
    }
  } catch (error) {
    console.error('聊天请求出错:', error);
    
    // 最终的错误处理，返回一个友好的响应
    return {
      content: "抱歉，我现在无法回复你，请稍后再试～",
      mood: 60,
      imageUrl: null
    };
  }
};

// 获取虚拟恋人资料
export const getCompanionProfile = async () => {
  try {
    // 先检查API是否可用
    const apiAvailable = await checkApiAvailability();
    
    if (!apiAvailable) {
      throw new Error("API不可用，无法获取虚拟恋人资料");
    }
    
    const response = await axios.get(`${CURRENT_API_URL}/companion/profile`, {
      timeout: 3000
    });
    
    debugLog('获取虚拟恋人资料成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('获取虚拟恋人资料失败:', error);
    throw error; // 不再使用默认资料，直接抛出错误
  }
};

// 创建虚拟恋人资料
export const createCompanionProfile = async (data: {
  name: string;
  personality: string;
  interests: string[];
  background: string;
  style_type: string;
}) => {
  try {
    // 先检查API是否可用
    const apiAvailable = await checkApiAvailability();
    
    if (!apiAvailable) {
      throw new Error("API不可用，无法创建虚拟恋人资料");
    }
    
    const response = await axios.post(`${CURRENT_API_URL}/companion/profile`, data, {
      timeout: 3000
    });
    
    debugLog('创建虚拟恋人资料成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('创建虚拟恋人资料失败:', error);
    throw error; // 不再使用本地模拟，直接抛出错误
  }
};

// 获取场景列表
export function getScenarios(): Promise<any> {
  return axios.get(`${CURRENT_API_URL}/scenarios`)
    .then(res => res.data)
    .catch(error => {
      console.error('获取场景列表失败:', error);
      throw error; // 不再使用默认场景，直接抛出错误
    });
}

// 设置当前场景
export function setScenario(scenarioName: string): Promise<any> {
  return axios.post(`${CURRENT_API_URL}/scenario/${scenarioName}`)
    .then(res => res.data)
    .catch(error => {
      console.error('设置场景失败:', error);
      throw error; // 不再使用本地模拟，直接抛出错误
    });
}

// 获取对话历史
export function getConversationHistory(): Promise<any> {
  return axios.get(`${CURRENT_API_URL}/conversation/history`)
    .then(res => res.data)
    .catch(error => {
      console.error('获取对话历史失败:', error);
      throw error; // 不再使用本地历史，直接抛出错误
    });
}

